import { Image, List, InfiniteScroll } from "antd-mobile";
import { useEffect, useState } from "react";
import { articlesResType, getArticlesApi } from "@/apis/channels";
import { useNavigate } from "react-router-dom";

type Props = {
  channelId: string;
};
const HomeList = (props: Props) => {
  const { channelId } = props;
  const [listRes, setListRes] = useState<articlesResType>({
    results: [],
    pre_timestamp: "",
  });

  const getFetchData = async (timestamp: string, type: string = "init") => {
    try {
      const params = {
        channel_id: channelId,
        timestamp,
      };
      const {
        data: {
          data: { results, pre_timestamp },
        },
      } = await getArticlesApi(params);

      setHasMore(results.length === 10); //停止上拉加载更多

      setListRes({
        results: type === "init" ? results : [...listRes.results, ...results],
        pre_timestamp,
      });
    } catch (error) {
      throw new Error(`error: ${error}`);
    }
  };
  useEffect(() => {
    const timestamp = "" + new Date().getTime();
    getFetchData(timestamp);
  }, []);

  // 加载更多
  const [hasMore, setHasMore] = useState(false);
  async function loadMore() {
    await getFetchData(listRes.pre_timestamp, "append");
  }

  // 跳转详情页
  const navigate = useNavigate();
  const toDetail = (artId: number) => {
    // 跳转详情页
    // navigate(`/detail?art_id=${artId}`);
    navigate("/detail", { state: { artId } });
  };
  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item
            key={item.art_id}
            onClick={() => toDetail(item.art_id)}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
          >
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={50} />
    </>
  );
};

export default HomeList;
